#include <iostream>
#include <cstdio>
#include <cerrno>
#include <cstring>
#include <cassert>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "comm.hpp"

int main(){
    //创建管道文件
    umask(0);
    int n = mkfifo(fifoName.c_str(), mode);
    if(n != 0){
        cout << errno << ": " << strerror(errno) << endl;
        return 1;
    }
    cout << "create fifo file success" << endl;

    //服务端开启管道文件
    int rfd = open(fifoName.c_str(), O_RDONLY);
    if(rfd < 0){
        cout << errno << ": " << strerror(errno) << endl;
        return 2;
    }
    cout << "open fifo success, begin ipc" << endl;

    //正常通信
    char buffer[NUM];
    while(true){
        buffer[0] = 0;
        ssize_t n = read(rfd, buffer, sizeof(buffer) - 1);
        if(n > 0){
            buffer[n] = 0;
            cout << "client: " << buffer << endl;
        }
        else if(n == 0){
            cout << "client quit, me too" << endl;
            break;
        }
        else{
            cout << errno << ": " << strerror(errno) << endl;
            break;
        }
    }

    close(rfd);
    return 0;
}